import {
  Controller,
  Delete,
  Get,
  HttpStatus,
  Post,
  Put,
  Query,
  Req,
} from '@nestjs/common';
import { ApiHeader, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Request } from 'express';
import { NotifyService } from 'src/notify/notify.service';
import { ValidAuthFailDto } from 'src/user/dto/middleware/auth.middleware.dto';
import { ClockService } from './clock.service';
import {
  CreateClockReqDto,
  CreateClockResFailDto,
  CreateClockResSuccessDto,
} from './dto/create-clock.dto';
import {
  DeleteClockItemReqDto,
  DeleteClockItemResFailDto,
  DeleteClockItemResSucessDto,
} from './dto/delete-clockitem.dto';
import { GetClockResSuccessDto } from './dto/get-clock.dto';
import {
  SetClockItemReqDto,
  SetClockItemResFailDto,
  SetClockItemResSuccessDto,
} from './dto/set-clockitem.dto';
import {
  StartClockReqDto,
  StartClockResFailDto,
  StartClockResSuccessDto,
} from './dto/start-clock.dto';

@ApiTags('clock')
@ApiResponse({
  status: HttpStatus.FORBIDDEN,
  type: ValidAuthFailDto,
  description: '身份验证失败',
})
@Controller('clock')
export class ClockController {
  constructor(private readonly clockService: ClockService) {}

  @Get('clocks')
  @ApiHeader({
    name: 'token',
    description: '身份令牌',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: GetClockResSuccessDto,
    description: '获取番茄钟成功',
  })
  async getClocks(@Req() request: Request) {
    const openid = request['user'].openid;
    const clocks = await this.clockService.findOne(openid);

    const notifyService = new NotifyService();
    for (const clock of clocks ? clocks.clocks : []) {
      if (clock.playing) {
        // 从运行队列中，找到正在运行的任务，更新查询到剩余时间（target - now）
        const notify = await notifyService.findOne(openid, clock.id);
        clock.now_timestamp =
          clock.now_timestamp + (Date.now() - notify.start_timestamp);
      }
    }
    if (clocks) {
      return {
        success: true,
        clocks: clocks.clocks,
      };
    } else {
      return {
        success: true,
        clocks: [],
      };
    }
  }

  @Post('clocks-item')
  @ApiHeader({
    name: 'token',
    description: '身份令牌',
  })
  @ApiResponse({
    status: HttpStatus.CREATED,
    type: CreateClockResSuccessDto,
    description: '创建番茄钟成功',
  })
  @ApiResponse({
    status: HttpStatus.ACCEPTED,
    type: CreateClockResFailDto,
    description: '创建番茄钟失败',
  })
  async createClockAndClockItem(
    @Req() request: Request,
    @Query() query: CreateClockReqDto,
  ) {
    const openid = request['user'].openid;
    const { tags, target, name } = query;
    const result = await this.clockService.createClockAndClockItem(
      openid,
      name,
      target,
      tags,
    );
    return result;
  }

  @Delete('clocks-item')
  @ApiHeader({
    name: 'token',
    description: '身份令牌',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: DeleteClockItemResSucessDto,
    description: ' 删除番茄钟成功',
  })
  @ApiResponse({
    status: HttpStatus.ACCEPTED,
    type: DeleteClockItemResFailDto,
    description: '删除番茄钟失败',
  })
  async deleteClockItem(
    @Req() request: Request,
    @Query() query: DeleteClockItemReqDto,
  ) {
    const openid = request['user'].openid;
    const { id, type } = query;
    if (type === 'one') {
      if (typeof id === 'string') {
        await this.clockService.deleteClockItem(openid, id);
      } else {
        return {
          success: false,
        };
      }
    } else if (type === 'multiple') {
      if (id instanceof Array) {
        await this.clockService.deleteMultipleClockItem(openid, id);
      } else {
        return {
          success: false,
        };
      }
    }
    return {
      success: true,
    };
  }

  @Put('clocks-item')
  @ApiHeader({
    name: 'token',
    description: '身份令牌',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: SetClockItemResSuccessDto,
    description: ' 修改番茄钟成功',
  })
  @ApiResponse({
    status: HttpStatus.ACCEPTED,
    type: SetClockItemResFailDto,
    description: '修改番茄钟失败',
  })
  async setClockItem(
    @Query() query: SetClockItemReqDto,
    @Req() request: Request,
  ) {
    const openid = request['user'].openid;
    const { id, name, tags, target } = query;
    await this.clockService.setClockItem(openid, id, name, target, tags);
    return {
      success: true,
    };
  }

  @Put('clocks-item/playing')
  @ApiHeader({
    name: 'token',
    description: '身份令牌',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: StartClockResSuccessDto,
    description: ' 修改番茄钟状态成功',
  })
  @ApiResponse({
    status: HttpStatus.ACCEPTED,
    type: StartClockResFailDto,
    description: '修改番茄钟状态失败',
  })
  async changeClockState(
    @Req() request: Request,
    // @Body() body: StartClockReqDto,
    @Query() query: StartClockReqDto,
  ) {
    const openid = request['user'].openid;
    const { id, state } = query;
    if (state === 'start') {
      await this.clockService.startClock(openid, id);
    } else if (state === 'stop') {
      await this.clockService.stopClock(openid, id);
    }
    return {
      success: true,
    };
  }
}
